<?php

namespace App\Http\Controllers\Api\V1;


use App\Events\WechatLoginedEvent;
use App\Http\Resources\AdCollection;
use App\Http\Resources\User;
use App\Http\Resources\UserBuyOrderCollection;
use App\Http\Resources\UserListenedCollection;
use App\Logic\CommonLogic;
use App\Models\Ad;
use App\Models\AdPositionId;
use App\Models\Feedback;
use App\Models\ScanCode;
use App\Models\UserBuyOrder;
use App\Models\UserListened;
use Illuminate\Http\Request;

class MemberController extends BaseController
{
    public function index()
    {
        $user = $this->getUser();
        if ($user) {
            $user = \App\User::query()->with([
                'docs',
                'followings',
                'followers'
            ])->find($user->id);
            $data['user'] = User::make($user);

        }
        $data['web_host'] = config('wx.web_host');

        $ap = AdPositionId::query()->where('code', 'member-index-menu')->first();
        $grid_menu = Ad::query()->where('ad_position_id', $ap->id)->orderByDesc('order')->get();

        $data['menu'] = AdCollection::make($grid_menu);

        return $this->success($data);
    }

    public function edit_intro(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'intro' => 'required|max:15|alpha_num',
            'name' => 'required|max:8|alpha_num',
        ], [
            '*.required' => '请输入内容',
            '*.alpha_num' => '内容格式有误',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $intro = $request->input("intro");
        $name = $request->input("name");

        $content = $intro . $name;
        if (!CommonLogic::msg_sec_check($content)) {
            return $this->failed('内容含有敏感词');
        }
        $user = $this->getUser();
        $user->intro = $intro;
        $user->name = $name;
        $user->save();
        return $this->success(['name' => $name, 'intro' => $intro]);
    }

    public function get_login_key(Request $request)
    {
        $key = $request->input("key");
        $sc = ScanCode::query()->where('key', $key)->where('user_id', '0')->first();
        if (empty($sc)) {
            $data['state'] = false;
        } else {
            $sc->is_scan = 1;
            $sc->save();
            $data['state'] = true;
        }
        //$data['wx_config'] = $this->getWxConfig();
        event(new WechatLoginedEvent($key, [
            'state' => 1,
            'type' => 'success',
            'desc' => '扫码成功，正在等待授权'
        ]));
        return $this->success($data);
    }

    public function consent_login(Request $request)
    {
        $key = $request->input("key");
        $user = $this->getUser();
        $sc = ScanCode::query()->where('key', $key)->where('is_scan', 1)->where('user_id', '0')->first();
        if (empty($sc)) {
            return $this->failed('二维码不存在');
        } else {
            $sc->user_id = $user->id;
            $sc->save();
        }
        event(new WechatLoginedEvent($key, [
            'state' => 2,
            'type' => 'success',
            'desc' => '授权成功，正在跳转',
            'user' => User::make($user),
            'roles' => ['admin'],
            'token' => $user->createToken($user->id, ['web-open'])->accessToken,
            'web_token' => encrypt(json_encode(['user_id' => $user->id, 'time' => time()]))
        ]));
        return $this->message('授权成功');

    }

    public function order()
    {
        $user = $this->getUser();
        $order = UserBuyOrder::query()->where('user_id', $user->id)->where('pay_state', 1)->orderByDesc('pay_time');
        $page = $order->paginate();
        $data = UserBuyOrderCollection::make($page)->show(['item', 'item_type', 'pay_money', 'order_sn', 'pay_time'])
            ->relate([
                'doc' => ['show', 'id', 'title', 'cover']
            ]);
        return $this->success($data);
    }

    public function listened()
    {
        $user = $this->getUser();
        $listened = UserListened::query()->where('user_id', $user->id)->orderByDesc('updated_at');
        $listened->with([
            'item',
            'item.doc',
            'item.doc.listened' => function ($query) use ($user) {
                $query->where("user_id", $user->id);
            },
            'item.doc.pages',
            'item.doc.category',
        ]);
        $page = $listened->paginate();
        $data = UserListenedCollection::make($page)->relate([
            'doc_page' => ['show', 'id', 'title', 'updated_format', 'doc', 'link'],
            'doc' => ['show', 'id', 'cover', 'title', 'page_count', 'category_name', 'listened_count']
        ]);
        return $this->success($data);
    }


    public function feedback(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'content' => 'required|max:600',
            'images' => 'array'
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $user = $this->getUser();

        $fb = Feedback::query()->create([
            'user_id' => $user->id,
            'content' => $request->input("content"),
            'images' => json_encode($request->input("images"))
        ]);

        return $this->message('感谢您的反馈');
    }
}